import axios from 'axios';
import store from './store.js';

// 创建 axios 实例
const request = axios.create({
    baseURL: 'http://localhost:9595',
    timeout: 10000,
    withCredentials: true
});

// 响应拦截器
request.interceptors.response.use(
    response => {
        const res = response.data;
        if (res.code === 10000) {
            return res;
        }
        // 未登录或会话过期
        if (res.code === 40100) {
            store.clearCurrentUser();
            window.location.href = '/login.html?message=请先登录';
            return Promise.reject(new Error('请先登录'));
        }
        return Promise.reject(new Error(res.message || '未知错误'));
    },
    error => {
        console.error('响应错误:', error);
        return Promise.reject(error);
    }
);

export default request;